import { Toast } from 'antd-mobile';
import api from '../../config/api';

let count = 0;
let handle;
const http = {
  hiddenLoading() {
    if (count <= 0) {
      clearTimeout(handle);
      Toast.hide();
    }
  },
  showLoading() {
    count++;
    if (count === 1) {
      console.log('c', count);
      handle = setTimeout(() => {
        Toast.loading('loading...', 0);
      }, 1000);
    }
  },
  stringify(data = {}) {
    let esc = encodeURIComponent;
    let query = Object.keys(data)
      .map((k) => esc(k) + '=' + esc(data[k]))
      .join('&');
    return query;
  },
  checkStatus(res) {
    if (res.ok) return res;

    count = 0;
    this.hiddenLoading();
    const error = new Error('err');
    error.data = res;
    Toast.fail('请求错误');
    console.dir(res);
    throw error;
  },
  async _request(url, config = {}) {
    try {
      this.showLoading();
      let res = await fetch(api.proxy + url, config);
      let result = await this.checkStatus(res).json();
      count--;
      this.hiddenLoading();
      return result;
    } catch (error) {
      console.dir(error);
      if (error.toString() !== 'Error: err') {
        count = 0;
        this.hiddenLoading();
        Toast.fail('网络错误');
        throw error;
      }
    }
  },
  async get(url, data = {}) {
    let query = this.stringify(data);
    let s = url.indexOf('?') ? '&' : '?';
    return await this._request(url + s + query);
  },
  async post(url, data = {}) {
    let query = this.stringify(data);
    return await this._request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: query,
    });
  },
};

// 使用
// http.get(url,data).then(e=>{})
// reslut = http.get(url,data)

export default http;
